package sysUtil

import initConfig.SysInitData
import sysAuth.SysFunctions
import sysAuth.SysOperations
import sysAuth.SysRoleRela
import sysAuth.SysRoles
import sysAuth.SysUserRoles
import sysAuth.SysUsers

import javax.servlet.http.HttpSession

/**
 * Created by Administrator on 2018-05-12.
 */
class SysAuthUtil {

    /**
     *
     * @param startFunction 递归从父节点开始查找其子节点
     */
    public static listFuncTreeByList(Map parent, ArrayList<SysFunctions> childrens){
        if(childrens ){

            //记录已经插入的子节点
            //def removeNode = []
            //查找父节点
            //记录已经添加的节点，下次无需再次遍历

            for (int i=0;i<childrens.size();i++){
                def node = childrens.get(i).getMap()

                if(parent.id == node.parentId){
                    parent.children.add(node)
                    List newChilds = childrens.clone();
                    newChilds.remove(i)
                    //println "node :${parent.children} "
                    listFuncTreeByList(node,newChilds)
                }
            }
        }
    }


    /**
     * 获取菜单列表
     * @param sysRoles
     * @return
     */
    public static ArrayList<Map> getUserFuncListByRoles(List<SysRoles> sysRoles) {
        def castList = new ArrayList<Map>();
        if (sysRoles) {
            //判定角色编码
            def roleNos = sysRoles.roleNo
            //对象转换MAP
            if (roleNos.contains("ADMIN_FUNC_ROLE")) {
                //获取父节点
                List<SysFunctions> parentFunc = SysFunctions.findAllByParentIsNull([sort: "orderNum"])
                //获取除过父节点意外的所有节点
                List<SysFunctions> childrens = SysFunctions.findAllByIdNotInList(parentFunc.id, [sort: "orderNum"])

                for (SysFunctions parent : parentFunc) {
                    def data = parent.getMap()
                    castList.add(data)
                    SysAuthUtil.listFuncTreeByList(data, childrens)
                }
            } else {
                List<SysRoleRela> authFuncs = SysRoleRela.findAllByRoleTypeAndRoleIdInList("FUNC_ROLE", sysRoles.id)
                def parentFunc = SysFunctions.findAllByIdInListAndParentIdIsNull(authFuncs.dataId, [sort: "orderNum"])
                //println parentFunc
                List<SysFunctions> childrens = SysFunctions.findAllByIdNotInList(parentFunc.id, [sort: "orderNum"])
                for (def parent : parentFunc) {
                    def data = parent.getMap()
                    castList.add(data)
                    SysAuthUtil.listFuncTreeByList(parent, childrens)
                }
            }
        }
        return  castList;
    }


    /**
     * 获取用户角色权限
     * @return
     */
    public static List<SysRoles> getUserRolesBySession(session) {
        SysUsers user = session.getAttribute(SysInitData.SESSION_CURRENT_USER)
        List<SysUserRoles> userRoles = SysUserRoles.findAllByUserId(user.id)
        List<SysRoles> roles = SysRoles.findAllByIdInList(userRoles.roleId)
        //print "getUserRoleList ${roles[0]?.roleName}"
        return roles;
    }

    /**
     * 根据用户角色类型，获取用户角色权限
     * @return
     */
    public static List<SysRoles> getUserRolesBySessionAndRoleType(session,roleType) {
        SysUsers user = session.getAttribute(SysInitData.SESSION_CURRENT_USER)
        List<SysUserRoles> userRoles = SysUserRoles.findAllByUserId(user?.id)
        List<SysRoles> roles = SysRoles.findAllByIdInListAndRoleType(userRoles?.roleId,roleType)
        //print "getUserRoleList ${roles[0]?.roleName}"
        return roles;
    }

    /**
     * 根据用户角色类型，获取用户角色权限
     * @return
     */
    public static List<SysRoles> getUserRolesByUserNoAndRoleType(String userNo,String roleType) {
        SysUsers user = SysUsers.findByUserNo(userNo)
        List<SysUserRoles> userRoles = SysUserRoles.findAllByUserId(user?.id)
        List<SysRoles> roles = SysRoles.findAllByIdInListAndRoleType(userRoles.roleId,roleType)
        //print "getUserRoleList ${roles[0]?.roleName}"
        return roles;
    }

    /**
     * 根据用户获取用户角色权限，然后根据功能页面名称，获取该该页面操作权限
     * @param user
     * @param funcPath
     * @return
     */
    public static List<String> getOperateNosByUserAndFuncPath(SysUsers user,String funcPath){
        def func = SysFunctions.findByPath(funcPath)
        List<SysUserRoles> userRoles = SysUserRoles.findAllByUserId(user?.id)
        List<SysRoleRela> roleRelaList = SysRoleRela.findAllByRoleTypeAndDataIdAndRoleIdInList("FUNC_ROLE",func?.id,userRoles.roleId)

        def adminRole= SysRoles.findByRoleNo("ADMIN_FUNC_ROLE")
        List all = []
        StringBuffer sb = new StringBuffer()
        //判定是否为管理员角色
        if(roleRelaList.roleId.contains(adminRole?.id)){
            sb.append(func.getOperateNos())
        }else{
            roleRelaList.each {
                sb.append(it.getOperateNos())
            }
        }
        all = sb.toString()?.split(",")?.toList()?.unique()
        return all
    }

    /**
     *根据sql 获取总数
     * @param dataSource
     * @param sql
     * @return
     */
    public static long getSqlCount(dataSource,sql){
        def db = new groovy.sql.Sql (dataSource)
        def list = db.rows(SysAuthSQL.sqlCount(sql))
        long count = 0;
        if(list){
            count = list.get(0).COUNTN;
        }
        return  count;
    }

    /**
     * 根据sql，获取分页数据
     * @param dataSource
     * @param sql
     * @param page
     * @param limit
     * @return
     */
    public static List getSqlList(dataSource,String sql ,offset,maxRows){
        def db = new groovy.sql.Sql (dataSource)
        def list = db.rows(sql,offset,maxRows)
        return list
    }

    /**
     *
     * @param user
     * @param optType 操作权限类型：Toolbar;FormButton
     * @param params
     * function: 根据菜单获取，该菜单的操作权限
     */
    public static List getOptAuth(SysUsers user,String optType,Map params){
        String funcPath = params?.get("funcPath").toString()
        List list = SysAuthUtil.getOperateNosByUserAndFuncPath(user,funcPath)
        def result = []
        def sysOperations = SysOperations.findAllByType(optType)
        sysOperations.each {
            if(list.contains(it.operateNo)){
                result.add(it)
            }
        }
        //println "getOptAuth:${sysOperations}"
        return  result;
    }

    /**
     * 用户list
     * @param sql
     * @param offset
     * @param max
     * @return
     */
    public static List<SysUsers> getUserList(String sql,int offset,int max){
        def list = SysUsers.executeQuery(sql,[offset:offset?:0,max:max?:10])
        return list
    }
    public static long getUserListCount(String sql){
        def list = SysUsers.executeQuery(sql)
        return list.get(0);
    }

}
